<template>
  <n-card title="用户管理">
    <template #header-extra>
      <n-button type="primary" @click="handleAdd">
        <template #icon>
          <n-icon><AddIcon /></n-icon>
        </template>
        新增用户
      </n-button>
    </template>

    <n-data-table
      :loading="loading"
      :columns="columns"
      :data="tableData"
      :pagination="pagination"
      @update:page="handlePageChange"
    />
  </n-card>
</template>

<script setup lang="ts">
import { h, ref } from "vue";
import { NButton, NSpace, NPopconfirm } from "naive-ui";
import { AddIcon, EditIcon, TrashIcon } from "@/components/Icon";
import { Message } from "@/utils/message";

interface User {
  id: number;
  name: string;
  email: string;
  role: string;
  status: number;
  createTime: string;
}

const loading = ref(false);
const tableData = ref<User[]>([]);

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 40],
});

// 表格列配置
const columns = [
  {
    title: "用户名",
    key: "name",
  },
  {
    title: "邮箱",
    key: "email",
  },
  {
    title: "角色",
    key: "role",
  },
  {
    title: "状态",
    key: "status",
    render(row: User) {
      return h(
        NButton,
        {
          type: row.status === 1 ? "success" : "warning",
          size: "small",
          quaternary: true,
        },
        { default: () => (row.status === 1 ? "启用" : "禁用") }
      );
    },
  },
  {
    title: "创建时间",
    key: "createTime",
  },
  {
    title: "操作",
    key: "actions",
    render(row: User) {
      return h(NSpace, null, {
        default: () => [
          h(
            NButton,
            {
              type: "primary",
              size: "small",
              onClick: () => handleEdit(row),
            },
            {
              default: () => "编辑",
              icon: () => h(EditIcon),
            }
          ),
          h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete(row),
            },
            {
              default: () => "确认删除？",
              trigger: () =>
                h(
                  NButton,
                  {
                    type: "error",
                    size: "small",
                  },
                  {
                    default: () => "删除",
                    icon: () => h(TrashIcon),
                  }
                ),
            }
          ),
        ],
      });
    },
  },
];

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    // 模拟API请求
    const data = Array.from({ length: 10 }, (_, index) => ({
      id: index + 1,
      name: `用户${index + 1}`,
      email: `user${index + 1}@example.com`,
      role: index % 2 === 0 ? "管理员" : "普通用户",
      status: index % 3 === 0 ? 0 : 1,
      createTime: new Date().toLocaleString(),
    }));
    tableData.value = data;
    pagination.value.itemCount = 100; // 总条数
  } catch (error) {
    Message.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 页码改变
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  fetchUsers();
};

// 新增用户
const handleAdd = () => {
  Message.info("新增用户");
};

// 编辑用户
const handleEdit = (row: User) => {
  Message.info(`编辑用户：${row.name}`);
};

// 删除用户
const handleDelete = async (row: User) => {
  try {
    Message.success(`删除用户：${row.name}`);
    await fetchUsers();
  } catch (error) {
    Message.error("删除失败");
  }
};

// 初始化
fetchUsers();
</script>
